<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<style>
  #messages {
    border: 1px solid #ccc;
    padding: 10px;
    margin-top: 10px;
    height: 200px;
    overflow-y: scroll;
  }

  #input-area {
    margin-top: 10px;
  }
</style>
</head>
<body>

<h1>WebSocket Chat</h1>

<div id="messages">
  <!-- Messages will be displayed here -->
</div>

<div id="input-area">
  <input type="text" id="message-input" placeholder="Type your message...">
  <button id="send-button">Send</button>
</div>

<script>
  // 1. WebSocket 连接
  const websocket = new WebSocket('ws://localhost:8080/websocket/181268'); // Replace with your backend WebSocket URL

  // 2. 监听 WebSocket 事件
  websocket.addEventListener('open', (event) => {
    console.log('WebSocket connection opened!');
    appendMessage('System: Connected to server');
  });

  websocket.addEventListener('close', (event) => {
    console.log('WebSocket connection closed.');
    appendMessage('System: Disconnected from server');
  });

  websocket.addEventListener('error', (event) => {
    console.error('WebSocket error:', event);
    appendMessage('System: Error - ' + event.message);
  });

  websocket.addEventListener('message', (event) => {
    console.log('Message from server:', event.data);
    appendMessage('Server: ' + event.data);
  });

  // 3. 获取输入框和发送按钮
  const messageInput = document.getElementById('message-input');
  const sendButton = document.getElementById('send-button');

  // 4. 发送消息函数
  function sendMessage() {
    const message = messageInput.value.trim();
    if (message) {
      websocket.send(message);
      appendMessage('Client: ' + message);
      messageInput.value = ''; // Clear the input field
    }
  }

  // 5. 监听发送按钮点击事件
  sendButton.addEventListener('click', sendMessage);

  // 6. 监听输入框回车事件
  messageInput.addEventListener('keydown', (event) => {
    if (event.key === 'Enter') {
      sendMessage();
    }
  });

  // Helper function to append messages to the message div
  function appendMessage(message) {
    const messagesDiv = document.getElementById('messages');
    const messageElement = document.createElement('p');
    messageElement.textContent = message;
    messagesDiv.appendChild(messageElement);
    messagesDiv.scrollTop = messagesDiv.scrollHeight;
  }
</script>

</body>
</html>